package qs.openxt.libs.remoting;

import android.content.Context;
import android.widget.Toast;

import qs.openxt.libs.R;
import com.alibaba.fastjson.JSONObject;
import qs.openxt.libs.progress.Wait;
import qs.openxt.libs.util.ActivityUtil;

public class Remoting{
	protected Context context = null;
	protected String serverAddress = "";
	protected BusinessTask task = null;
	
	private boolean isShowDialogProgress = true;
	private JSONObject header = null;

	protected OnActionListener listener = null;

	public Remoting() {

	}
	public Remoting(Context context) {
		this.context = context;
	}
	public Remoting(Context context, OnActionListener l) {
		this.context = context;
		this.listener = l;
	}

	public void setOnActionListener(OnActionListener l) {
		this.listener = l;
	}

	public void setServerAddress(String serverAddress) {
		this.serverAddress = serverAddress;
	}
	
	public void setShowDialogProgress(boolean isShowDialogProgress) {
		this.isShowDialogProgress = isShowDialogProgress;
	}

	public void setHeader(JSONObject header) {
		this.header = header;
	}

	public void doRequest(JSONObject params) {
		if(context != null && !ActivityUtil.isNetworkAvailable(context)){
			Toast.makeText(context, context.getString(R.string.isNetworkAvailable), Toast.LENGTH_SHORT).show();
			return;
		}
		
		if(context != null && isShowDialogProgress)
			Wait.sharedInstance().start(context, "正在通讯...，请稍候");

		try {
			JSONObject json = new JSONObject();
			
			Client client = new Client();
			client.setServerAddress(serverAddress);
			client.setHeader(header);
			json.put("client", client);
			json.put("args", params);
			task = new BusinessTask(this);
			task.execute(json);
		} catch (Exception e) {
			Wait.sharedInstance().stop();
		}
	}

	public void doRequest(JSONObject params, String method) {
		if (context != null && !ActivityUtil.isNetworkAvailable(context)) {
			Toast.makeText(context, context.getString(R.string.isNetworkAvailable), Toast.LENGTH_SHORT).show();
			onError(null);
			return;
		}

		if (context != null && isShowDialogProgress)
			Wait.sharedInstance().start(context, "正在通讯...，请稍候");

		try {
			JSONObject json = new JSONObject();

			Client client = new Client();
			client.setMethod(method);
			client.setHeader(header);
			client.setServerAddress(serverAddress);
			json.put("client", client);
			json.put("args", params);
			task = new BusinessTask(this);
			task.execute(json);
		} catch (Exception e) {
			Wait.sharedInstance().stop();
		}
	}

	public void onSuccess(String reVal) {
		Wait.sharedInstance().stop();

		if (listener != null) {
			listener.onActionCompleted(reVal);
		}
	}

	public void onError(String errorVal) {
		Wait.sharedInstance().stop();

		if (listener != null) {
			listener.onActionFailed(errorVal);
		}
	}

	public interface OnActionListener {
		public void onActionCompleted(String reVal);

		public void onActionFailed(String errorVal);
	}
}
